import request from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/types.d';
import type { BindedWxItem, ModifyPassword, UpdateSelfType } from './types.d';

export async function updateSelfInfo(id: string, newInfo: UpdateSelfType) {
  if (!id || !newInfo || Object.keys(newInfo).length === 0) {
    return { success: false, message: '更新失败，请填入需要更新的信息' };
  }
  const res = await request(`/api/sys-users/v1.0.0/self/${id}`, {
    method: 'PUT',
    data: newInfo,
  });
  if (res?.code === SUCCESS_CODE) return { success: true, data: res.data, message: '更新成功' };
  return { success: false, data: res?.data, message: res?.message || '更新失败' };
}
export async function updatePassword(id: string, newInfo: ModifyPassword) {
  if (!id || !newInfo || Object.keys(newInfo).length !== 2) {
    return { success: false, message: '更改失败，请填入需要的密码信息' };
  }
  const res = await request(`/api/sys-users/v1.0.0/self-password/${id}`, {
    method: 'PUT',
    data: newInfo,
  });
  if (res?.code === SUCCESS_CODE)
    return { success: true, data: res.data, message: '更改成功，请重新登录' };
  return { success: false, data: res?.data, message: res?.message || '更改失败' };
}

export async function bindWx(code: string) {
  if (!code) return { success: false, message: '缺少code参数', data: null };
  const res = await request('/api/sys-users/v1.0.0/wx/bind', {
    method: 'POST',
    data: { code },
  });
  if (res?.code === SUCCESS_CODE) return { success: true, data: res.data, message: '绑定成功' };
  return { success: false, data: res?.data, message: res?.message || '绑定失败' };
}

export async function queryBindedList(
  params: any,
  sort: any,
): Promise<{
  success: boolean;
  total: number;
  data: BindedWxItem[];
}> {
  const res = await request('/api/sys-users/v1.0.0/wx/binded-list', {
    method: 'GET',
    params: {
      data: params,
      sort,
    },
  });
  if (res?.code === SUCCESS_CODE)
    return { success: true, total: res?.data?.total || 0, data: res?.data?.data || [] };
  return { success: false, total: 0, data: [] };
}

export async function unbindWx(id: string) {
  if (!id) return { success: false, message: '缺少必要参数', data: null };
  const res = await request(`/api/sys-users/v1.0.0/wx/unbind`, {
    method: 'DELETE',
    data: {
      wxid: id,
    },
  });
  if (res?.code === SUCCESS_CODE) return { success: true, data: res.data, message: '解绑成功' };
  return { success: false, data: res?.data, message: res?.message || '解绑失败' };
}

export async function getUserResource() {
  const res = await request('/api/sys-users/v1.0.0/resource', {
    method: 'GET',
  });
  if (res?.code === SUCCESS_CODE) return { success: true, data: res.data, message: '获取成功' };
  return { success: false, data: res?.data, message: res?.message || '获取失败' };
}
